package com.sinosoft.ci.patch.yqscm;

import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.*;

import java.io.File;
import java.io.IOException;

/**
 * Java 源代码文件提取器
 *
 * Created by 韩朝祥 on 2017/5/26.
 */
public class JavaSrcExtractor {
  private Workbook workbook;
  private File srcDir;

  /**
   *
   * @param sheetFile 发布清单文件
   * @param srcDir 工程源码根目录
   */
  public JavaSrcExtractor(File sheetFile, File srcDir){
    try {
      workbook = WorkbookFactory.create(sheetFile);
    }catch (Exception ex){
      System.err.println(String.format("文件 %s 不是一个合法的 Excel 文件", sheetFile.getAbsolutePath()));
    }
    if(!srcDir.isDirectory()){
      throw new RuntimeException(String.format("路径 %s 不是一个合法的目录", srcDir.getAbsolutePath()));
    }
    this.srcDir = srcDir;
  }

  /**
   * 开始文件提取
   */
  public void extracte(File distDir){
    distDir.mkdirs();
    Sheet sheet = workbook.getSheet("JAVA");
    int lastRowNum = sheet.getLastRowNum();
    for (int i = 6; i <= lastRowNum; i++) {
      Row row = sheet.getRow(i);
      if(row == null){
        continue;
      }
      extracteFile(row, distDir);
    }
  }

  private void extracteFile(Row row, File distDir){
    Cell fileCell = row.getCell(2);
    Cell dirCell = row.getCell(3);
    if(null == fileCell || dirCell == null){
      return;
    }
    String path = dirCell.getStringCellValue() + fileCell.getStringCellValue();
    File srcFile = new File(srcDir, path);
    if(!srcFile.isFile()){
      System.err.println(String.format("%s 文件不存在", srcFile.getAbsolutePath()));
      return;
    }
    try {
      FileUtils.copyFile(srcFile, new File(distDir, path));
    }catch (IOException ex){
      ex.printStackTrace();
    }
  }
}
